package junior.db.dao.update;

import junior.db.dao.base.MybatisHelper;
import junior.db.dao.ext.IExtensible;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wubo
 * @date 2024/8/30 17:37
 */
public class UpdateFieldOption extends AbstractUpdateOption<UpdateFieldOption> implements IExtensible {
    protected Object[] updateValues;
    private Map<String, Object> ext;
    private List<String> extFields;
    
    public UpdateFieldOption(String field, Object value) {
        super.withUpdateValue(field, value);
    }
    
    public UpdateFieldOption(String field1, Object value1, String field2, Object value2) {
        super.withUpdateValue(field1, value1);
        super.withUpdateValue(field2, value2);
    }
    
    public UpdateFieldOption(String field1, Object value1, String field2, Object value2, String field3, Object value3) {
        super.withUpdateValue(field1, value1);
        super.withUpdateValue(field2, value2);
        super.withUpdateValue(field3, value3);
    }
    
    public Object[] getUpdateValues() {
        return updateValues;
    }
    
    @Override
    public void beforeExecuteNode() {
        initFields();
        initValues();
    }
    
    @Override
    public IExtensible doEntityExt(List<String> fields) {
        this.extFields = fields;
        return this;
    }
    
    @Override
    public IExtensible doExt(Map<String, Object> ext, List<String> fields) {
        this.extFields = fields;
        this.ext = ext;
        return this;
    }
    
    protected void initFields() {
        Set<String> fields = new HashSet<>();
        if (updateFieldValueMap != null) {
            fields.addAll(updateFieldValueMap.keySet());
        }
        if (fieldExpressionMap != null) {
            fields.addAll(fieldExpressionMap.keySet());
        }
        if (extFields != null) {
            fields.addAll(extFields);
        }
        
        updateFields = fields.toArray(new String[0]);
    }
    
    protected void initValues() {
        updateValues = new Object[updateFields.length];
        
        for (int i=0; i<updateFields.length; i++) {
            String field = updateFields[i];
            updateValues[i] = getValue(field);
        }
    }
    
    protected Object getValue(String field) {
        if (ext != null && ext.containsKey(field)) {
            return ext.get(field);
        }
        String expression = fieldExpressionMap == null ? null : fieldExpressionMap.get(field);
        if (expression != null) {
            return MybatisHelper.sqlToSqlValue(namespace, entityClass, expression, f -> updateFieldValueMap.get(f));
        }
        return updateFieldValueMap.get(field);
    }
    
}
